package com.apes.scm.masterdata.enumeration.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.event.Listener;
import com.apes.scm.masterdata.enumeration.model.BusinessParam;
import com.apes.scm.masterdata.enumeration.repository.BusinessParamRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BusinessParamService extends DomainService {

    @Autowired
    public BusinessParamRepository businessParamRepository;

    /**
     * 功能：上级公司
     **/
    public BusinessParam getParentCompany(SimpleRequest request) {
        String companyId = request.get("companyId");
        return businessParamRepository.findOne(JpaDsl.toCriteriaByEq(
                "queryKey", "accordingToCompanyContract", "value2", companyId)).orElse(null);
    }

    @Listener(topic = "event:businessParam.findOne")
    public BusinessParam findOne(SimpleRequest request) {
        return businessParamRepository.findOne((String) request.get("id"));
    }

    public boolean isDirectlyCompany(SimpleRequest request) {
        String companyId = request.get("companyId");
        return businessParamRepository.findAll(JpaDsl.toCriteriaByEq(
                "queryKey", "accordingToCompanyContract", "value", companyId)).size() > 0;
    }

    public JSONObject findAllByQueryKey(SimpleRequest request){
        JSONObject getJO = request.getJO();
        String queryKey = getJO.getString("queryKey");
        List<BusinessParam> allByQueryKey = businessParamRepository.findAllByQueryKey(queryKey);
        JSONObject js = new JSONObject();
        js.put("value",allByQueryKey.get(0).getValue());
        js.put("value3",allByQueryKey.get(0).getValue3());
        return js;
    }
}
